package org.wzq.controller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * project: spring-mvc-forum
 * ate: 14-9-16
 * author: wzq
 * description: TODO
 */

@Controller
public class TestController {
    protected final Log logger = LogFactory.getLog(getClass());

    public void printReq(HttpServletRequest req) {
        logger.info(req.getMethod() + "  " + req.getRequestURI());
    }

    @RequestMapping(value = {"/test"}, method = RequestMethod.GET)
    public ModelAndView home(HttpServletRequest req, HttpServletResponse res) throws IOException {
        printReq(req);
        Map<String, Object> map = new HashMap<String, Object>();
        return new ModelAndView("test", "map", map);
    }

    /**
     * 自己处理文件上传，未完成 TODO
     *
     * @throws IOException
     */
    @RequestMapping(value = "test/uploadFileSelf", method = {RequestMethod.POST})
    public ModelAndView uploadFileSelf(HttpServletRequest req, HttpServletResponse res) throws IOException {
        printReq(req);
        String contentType = req.getHeader("Content-type");
        System.out.println("contentType = " + contentType);
        int indexStart = contentType.indexOf("boundary=");
        indexStart = indexStart > 0 ? indexStart + "boundary=".length() : indexStart;

        int indexEnd = contentType.indexOf(";", indexStart);
        indexEnd = indexEnd < 0 ? contentType.length() : indexEnd;

        String boundary = contentType.substring(indexStart, indexEnd);
        System.out.println("boundary = " + boundary);

        // todo
        /*
        注意，在引入common-file-upload后，Stream就被拦截了
        req.getInputStream()不可用了
             <!--多文件上传-->
        <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- setting maximum upload size -->
        <property name="maxUploadSize" value="100000"/>
        </bean>
        */
        //----------------获取文件/表单 ------------------
        // startwith '--${boundary}' endwith '--${boundary}--'
        InputStream in = req.getInputStream();
        if (in != null) {
            System.out.println("in.available = " + in.available());
            String s = IOUtils.stream2String(in, "utf8");
            System.out.println("s = " + s);
        } else {
            System.out.println("null inputstream");
        }

        return new ModelAndView("zz");
    }

    /**
     * 单个文件上传
     *
     * @throws IOException
     */
    @RequestMapping(value = "test/uploadFile", method = {RequestMethod.POST})
    @ResponseBody
    public String uploadFile(@RequestParam("name") String name, @RequestParam("file") MultipartFile file)
            throws IOException {
        if (file.isEmpty()) {
            System.out.println("null file");
            return "null file";
        }

        // save the file
        byte[] bytes = file.getBytes();
        // Creating the directory to store file
        String rootPath = System.getProperty("catalina.home");
        File dir = new File(rootPath + File.separator + "tmpFiles");
        if (!dir.exists())
            dir.mkdirs();

        // Create the file on server
        File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
        stream.write(bytes);
        stream.close();

        logger.info("Server File Location=" + serverFile.getAbsolutePath());
        return "You successfully uploaded file=" + name;
    }

    /**
     * 多个文件上传
     */
    @RequestMapping(value = "test/uploadMultipleFile", method = {RequestMethod.POST})
    @ResponseBody
    public String uploadMultiFile(@RequestParam("name") String[] names, @RequestParam("file") MultipartFile[] files)
            throws IOException {

        if (names.length != files.length) {
            return "Mandatory information missing";
        }


        String message = "";
        for (int i = 0; i < names.length; i++) {
            MultipartFile file = files[i];
            String name = names[i];
            try {
                byte[] bytes = file.getBytes();

                // Creating the directory to store file
                String rootPath = System.getProperty("catalina.home");
                File dir = new File(rootPath + File.separator + "tmpFiles");
                if (!dir.exists())
                    dir.mkdirs();

                // Create the file on server
                File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();

                logger.info("Server File Location=" + serverFile.getAbsolutePath());
                message = message + "You successfully uploaded file=" + name + "<br />";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        }
        return message;
    }
}
